(in-package :cl-gdbm)

;; This should set a couple keys and return their values
(with-open-db (db "/root/lisp/gdbm/test.db" :mode :write)
  (store db "bar" "Not to be confused with pipe")
  (store db "baz" "The third one. Really.")
  (values (fetch db "baz") (fetch db "bar")))

;; Open the DB for reading and fetch some keys. The "foo" key doesn't
;; exist, so its value should be nil. It should also signal a warning,
;; which will be muffled in this case.
(with-open-db (db "/root/lisp/gdbm/test.db" :mode :read)
  (handler-bind ((key-not-found #'muffle-warning))
    (values (fetch db "foo") (fetch db "bar") (fetch db "baz"))))

(with-open-db (db "/root/lisp/gdbm/test.db" :mode :write)
  (setf (getkey db "a key") "a value")
  (getkey db "a key"))

;; Test key deletion and existence testing
(handler-bind ((key-not-found #'muffle-warning))
  (with-open-db (db "/root/lisp/gdbm/test.db" :mode :write)
    (setf (getkey db 'to-be-deleted) 42)
    (format t "~&The value now is ~S, and exists-p is ~S~%"
	    (getkey db 'to-be-deleted)
	    (key-exists-p db 'to-be-deleted))
    (princ "Deleting key...")
    (delete-key db 'to-be-deleted)
    (format t "~&The value now is ~S, and exists-p is ~S~%"
	    (getkey db 'to-be-deleted)
	    (key-exists-p db 'to-be-deleted))))

;; (values 666 nil 42 42)
(handler-bind ((key-not-found #'muffle-warning))
  (with-open-db (db "/root/lisp/gdbm/test.db" :mode :write)
    (delete-key db 'my-key)
    (values (handler-bind ((key-not-found #'(lambda (c) (use-value 666 c))))
	      (getkey db 'my-key))
	    (getkey db 'my-key)
	    (handler-bind ((key-not-found #'(lambda (c) (store-value 42 c))))
	      (getkey db 'my-key))
	    (getkey db 'my-key))))

(with-open-db (db "/root/lisp/gdbm/test.db" :mode :write)
  (values (sync-db db)
	  (reorganize-db db)))

(with-open-db (db "/root/lisp/gdbm/test.db" :mode :write)
  (values (keys-of db)
	  (db->alist db)))

(with-open-db (db "/root/lisp/gdbm/test.db" :mode :write)
  (set-syncmode db t)
  (set-cachesize db 100)
  (values (keys-of db)
	  (db->alist db))
  (set-syncmode db nil))